import React, { useRef } from 'react';
import { Button } from 'antd'
import * as XLSX from 'xlsx'
import filesaver from 'file-saver'
import { notification } from 'antd'
import "./Excel.scss"

function Excel() {
    var ref = useRef()
    var handleExport = ()=>{
        //导出的逻辑: 先发请求从服务器获取需要下载的数据,然后调用saveAs方法生成文件下载到本地.
        //发请求
        //...
        //调用saveAs方法生成文件下载到本地.
        // filesaver.saveAs( new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"}),'abc.txt');
        excelExport(document.querySelector('table'),'export');
    }
    var handleImport = ()=>{
        ref.current && ref.current.click();
    }
    //导入
    var httpRequest = (data) => {
        const file = data.target.files[0]
        const types = file.name.split('.')[1]
        const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt'].some(
          (item) => item === types
        )

        if (!fileType) {
          notification.error({message:'格式错误！请重新选择'});
          return
        }
        
        // 方式1（官网推荐、如果有报错就使用方式2）：
        file.arrayBuffer().then((ab) => {
          /* Parse file */
          const wb = XLSX.read(ab);
          const ws = wb.Sheets[wb.SheetNames[0]];
      
          /* Generate HTML */
          var output = document.getElementById('TableContainer') || document.body;
          output.innerHTML = XLSX.utils.sheet_to_html(ws)
        });
      
        // 方式2：
        // const reader = new FileReader()
        // reader.readAsArrayBuffer(file)
        // // reader.readAsArrayBuffer(new Blob([file]))
        // reader.onloadend = function (e) {
        //   const data = e.target.result
        //   const wb = XLSX.read(data, {
        //     type: 'buffer'
        //   })
      
        //   const ws = wb.Sheets[wb.SheetNames[0]]
        //   /* Generate HTML */
        //   var output = document.getElementById('TableContainer') || document.body;
        //   output.innerHTML = XLSX.utils.sheet_to_html(ws)
        // }
    }
    //导出
    var excelExport = (table, filename) => {
      // workbook,
      const wb = XLSX.utils.table_to_book(table)
    
      /* Export to file (start a download) */
      const defaultCellStyle = {
        font: { name: 'Verdana', sz: 13, color: 'FF00FF88' },
        fill: { fgColor: { rgb: 'FFFFAA00' } },
      }
      const wopts = {
        bookType: 'xlsx',
        bookSST: false,
        type: 'binary',
        cellStyle: true,
        defaultCellStyle: defaultCellStyle,
        showGridLines: false,
      }
      const wbout = XLSX.write(wb, wopts)
      const blob = new Blob([ s2ab(wbout)], { type: 'application/octet-stream' })
      filesaver.saveAs(blob, filename+'.xlsx')
    }
    // 字符串转字符流---转化为二进制的数据流
    var s2ab = (s) => {
      if (typeof ArrayBuffer !== 'undefined') {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
      } else {
        const buf = new Array(s.length);
        for (let i = 0; i !== s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff;
        return buf;
      }
    }
    return (
        <div className='excel'>
            {/* 操作 */}
            <div className="opts">
                <input ref={ref} type="file" onChange={httpRequest} />
                <Button onClick={handleImport}>导入</Button>
                <Button onClick={handleExport}>导出</Button>
            </div>
            <div id="TableContainer"></div>
        </div>
    );
}

export default Excel;